package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.entity.Role;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import com.atguigu.service.RoleService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @PACKAGE_NAME: com.atguigu.controller
 * @CLASSNAME: IndexController
 * @AUTHOR: zhangsan
 * @DATE: 2024/4/15 10:02
 * @SINCE 17.0.7
 * @DESCRIPTION: 框架首页
 */
@Controller
public class IndexController {

    private static final String PAGE_INDEX = "frame/index";
    private static final String PAGE_MAIN = "frame/main";

    private static final String PAGE_AUTH = "frame/auth";

    @Reference
    private AdminService adminService;

    @Reference
    private RoleService roleService;

    @Reference
    private PermissionService permissionService;

    @RequestMapping("/")
    public String index(Model model) {
        //后续替换为当前登录用户id
        //Long adminId = 1L;
        //if (null == adminId) return null;
        //Admin admin = adminService.getById(adminId);
        // spring-security 登录
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        Admin admin = adminService.getByUsername(user.getUsername());

        List<Permission> menuPermissionList = permissionService.findMenuPermissionByAdminId(admin.getId());

        List<Role> roleList = roleService.findRolesByAdminId(admin.getId());
        List<String> roleNameList = roleList.stream().map(Role::getRoleName).collect(Collectors.toList());

        model.addAttribute("roleNameList", roleNameList);
        model.addAttribute("permissionList", menuPermissionList);
        model.addAttribute("admin", admin);
        return PAGE_INDEX;
    }

    @RequestMapping("/main")
    public String main() {
        return PAGE_MAIN;
    }

    @RequestMapping("/getInfo")
    @ResponseBody
    public Object getInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getPrincipal();
    }

    @RequestMapping("/loginPage")
    public String toLoginPage() {
        return "frame/login";
    }

    @RequestMapping("/auth")
    public String auth() {
        return PAGE_AUTH;
    }

}
